package org.wishwork.api.inventory.query;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.wishwork.api.Api;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: WangYX
 * @create: 2022-04-06 11:05
 * @Version: 1.0.0
 **/

public class InventoryQueryApi extends Api<List<InventoryQueryResponse>, InventoryQueryRequest> {

    

    private Context context;

    public InventoryQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(InventoryQueryRequest inventoryQueryRequest) throws Exception {
        String url = "/open/inventory/query";
        Map<String, Object> params = new HashMap<>();
        if (inventoryQueryRequest.getWmsCoId() != null) {
            params.put("wms_co_id", inventoryQueryRequest.getWmsCoId());
        }
        if (inventoryQueryRequest.getSkuIds() != null) {
            params.put("sku_ids", inventoryQueryRequest.getSkuIds());
        }
        return HttpHelper.sendRequest(inventoryQueryRequest, params, url);
    }

    @Override
    protected List<InventoryQueryResponse> process(JSONObject data, InventoryQueryRequest inventoryQueryRequest) throws Exception {
        JSONArray inventorys = data.getJSONArray("inventorys");
        List<InventoryQueryResponse> inventoryQueryResponses = inventorys.toJavaList(InventoryQueryResponse.class);
        //判断是否还有下一个
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer index = inventoryQueryRequest.getPageIndex();
            InventoryQueryRequest build = inventoryQueryRequest.toBuilder().pageIndex(++index).build();
            List<InventoryQueryResponse> result = business(build);
            inventoryQueryResponses.addAll(result);
        }
        return inventoryQueryResponses;
    }
}
